const express = require('express');
const router = express.Router();
const query = require("../util/db.js")
const R = require("../util/resultJson.js")

router.get("/",function (req,res) {
    res.render("records/records-list")
})


router.post("/save",function (req,res) {
    const {applyId,count} = req.body;
    const userId = req.loginInfo.id;
    let sql = "insert into records values (null,?,?,?,?)";
    query(sql,[applyId,userId,count,new Date()]).then(()=>{
        sql = "update apply set status = 2 where id = ?";
        query(sql,[applyId]).then(()=>{
            res.json(R.success());
        })
    })
})

router.get("/page",function (req,res) {
    const {page,limit,goodsId,type,optTime} = req.query;
    const userId = req.loginInfo.role === 3?req.loginInfo.id:req.query.userId;
    const optId = req.loginInfo.role === 2?req.loginInfo.id:req.query.optId;
    let sql = "select r.*,u1.username applyName,u2.username optName,g.name goodsName,a.type,a.count applyCount from records r left join apply a on r.apply_id = a.id left join userinfo u1 on a.user_id = u1.id left join userinfo u2 on r.opt_id = u2.id left join goods g on a.goods_id = g.id where 1 = 1 ";
    const objs = [];
    if(goodsId){
        sql+="and a.goods_id = ? ";
        objs.push(goodsId);
    }
    if(userId){
        sql+="and a.user_id = ? ";
        objs.push(userId);
    }
    if(type){
        sql+="and a.type = ? ";
        objs.push(type);
    }
    if(optId){
        sql+="and r.opt_id = ? ";
        objs.push(optId)
    }
    if(optTime){
        const otr = optTime.split(" - ");
        sql+="and r.opt_time between ? and ? ";
        objs.push(otr[0]);
        objs.push(otr[1]);
    }
    query(sql,objs).then(list=>{
        const count = list.length;
        sql+="order by r.id desc limit ?,?";
        objs.push((page-1)*limit);
        objs.push(parseInt(limit));
        query(sql,objs).then(recordsList=>{
            res.json(R.page(count,recordsList));
        })
    })
})

router.delete("/delete/:id",function (req,res){
    let sql = "delete from records where id = ?";
    query(sql,[req.params.id]).then(()=>{
        res.json(R.success());
    })
})

module.exports = router;
